<template>
	<div class="app-container">
		<el-card class="card-container">
			<div slot="header" class="card-header">
				<span>维修统计</span>
			</div>

		<!-- 统计卡片 -->
		<div class="card-box">
			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>工单总数</span>
				</div>
				<div class="num-container">
					<span class="num-font">{{ repair_total }}</span>
				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>已完成工单</span>
				</div>
				<div class="num-container">
					<span class="num-font green">
						{{ repair_completed }} ({{ repair_completed_rate }}%)
					</span>
				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>平均处理时长</span>
				</div>
				<div class="num-container">
					<span class="num-font blue">
						{{ avg_process_time }}小时
					</span>
				</div>
			</el-card>

			<el-card class="box-card">
					<div slot="header" class="card-header">
						<span>待处理工单</span>
					</div>
					<div class="num-container">
						<span class="num-font red">{{ repair_pending }}</span>
					</div>
				</el-card>
				<el-card class="box-card">
					<div slot="header" class="card-header">
						<span>实际总成本</span>
					</div>
					<div class="num-container">
						<span class="num-font red">¥{{ total_actual_cost.toFixed(2) }}</span>
					</div>
				</el-card>
				<el-card class="box-card">
					<div slot="header" class="card-header">
						<span>估计总成本</span>
					</div>
					<div class="num-container">
						<span class="num-font blue">¥{{ total_estimated_cost.toFixed(2) }}</span>
					</div>
				</el-card>
		</div>

		<!-- 工单状态统计图表 -->
		<div class="chart-container">
			<el-card class="chart-card">
				<div slot="header" class="card-header">
					<span>工单状态分布</span>
				</div>
				<div class="chart-box">
					<el-row :gutter="20">
						<el-col :span="16">
							<div id="repairStatusChart" class="chart"></div>
						</el-col>
						<el-col :span="8">
							<el-table :data="repair_status_list" style="width: 100%">
								<el-table-column prop="statusName" label="工单状态"></el-table-column>
								<el-table-column prop="count" label="数量"></el-table-column>
								<el-table-column prop="rate" label="占比"></el-table-column>
							</el-table>
						</el-col>
					</el-row>
				</div>
			</el-card>
		</div>

		<!-- 工单趋势图表 -->
		<div class="chart-container">
			<el-card class="chart-card">
				<div slot="header" class="card-header">
					<span>工单趋势分析</span>
				</div>
				<div class="chart-box">
					<div id="repairTrendChart" class="chart"></div>
				</div>
			</el-card>
		</div>

		<!-- 维修人员统计 -->
		<div class="chart-container">
			<el-card class="chart-card">
				<div slot="header" class="card-header">
					<span>维修人员工作量统计</span>
				</div>
				<div class="chart-box">
					<div id="maintainerChart" class="chart"></div>
				</div>
			</el-card>
		</div>

		<!-- 工单列表 -->
		<div class="table-container">
			<el-card class="table-card">
				<div slot="header" class="card-header">
					<span>最近工单列表</span>
				</div>
				<el-table
						:data="repair_list"
						style="width: 100%"
						border
						stripe>
					<!-- <el-table-column prop="id" label="工单编号"></el-table-column> -->
					<el-table-column prop="requestCode" label="申请编号"></el-table-column>
					<el-table-column prop="deviceName" label="设备名称">
						<template slot-scope="scope">
							<span v-if="scope.row.deviceId && deviceMap[scope.row.deviceId]">{{ deviceMap[scope.row.deviceId].deviceName }}</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column prop="faultDescription" label="故障描述"></el-table-column>
					<el-table-column prop="priority" label="优先级">
						<template slot-scope="scope">
							<span v-if="scope.row.priority === 1">低</span>
							<span v-else-if="scope.row.priority === 2">普通</span>
							<span v-else-if="scope.row.priority === 3">紧急</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column prop="repairUserId" label="维修人员">
						<template slot-scope="scope">
							<span v-if="scope.row.repairUserId">维修员{{ scope.row.repairUserId }}</span>
							<span v-else>未分配</span>
						</template>
					</el-table-column>
					<el-table-column prop="requestTime" label="申请时间">
						<template slot-scope="scope">
							{{ formatDate(scope.row.requestTime) }}
						</template>
					</el-table-column>
					<el-table-column prop="status" label="工单状态">
						<template slot-scope="scope">
							<el-tag size="small" v-if="scope.row.status === 0" type="info">待处理</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 1" type="warning">处理中</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 2" type="danger">已取消</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 3" type="success">已完成</el-tag>
							<el-tag size="small" v-else type="info">其他</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="completionTime" label="完成时间">
						<template slot-scope="scope">
							{{ formatDate(scope.row.completionTime) }}
						</template>
					</el-table-column>
					<el-table-column prop="actualCost" label="实际成本">
						<template slot-scope="scope">
							¥{{ scope.row.actualCost || 0 }}
						</template>
					</el-table-column>
					<el-table-column prop="estimatedCost" label="估计成本">
						<template slot-scope="scope">
							¥{{ scope.row.estimatedCost || 0 }}
						</template>
					</el-table-column>
					<el-table-column prop="repairRemarks" label="维修备注"></el-table-column>
				</el-table>
				<el-pagination
					@size-change="handle_size_change"
					@current-change="handle_current_change"
					layout="total, sizes, prev, pager, next, jumper"
					:page-sizes="[10, 20, 50, 100]"
					:current-page="page_num"
					:page-size="page_size"
					:total="repair_total">
				</el-pagination>
			</el-card>
		</div>
		</el-card>
	</div>
</template>

<script>
	import repairApi from '@/api/repair-request.js'
	import deviceApi from '@/api/device.js'
	export default {
		name: "RepairStatistics",
		data() {
			return {
				total: 0,
				page_size: 10,
				page_num: 1,

				// 统计数据
			repair_total: 0,
			repair_completed: 0,
			repair_pending: 0,
			repair_completed_rate: 0,
			avg_process_time: 0,
			// 成本统计
			total_actual_cost: 0,
			total_estimated_cost: 0,
			cost_diff_rate: 0,
				// 设备信息映射
				deviceMap: {},
				// 图表数据
				repair_status_list: [],
				repair_trend_list: [],
				maintainer_list: [],

				// 工单列表
				repair_list: [],

				// 图表实例
				repair_status_chart: null,
				repair_trend_chart: null,
				maintainer_chart: null
			}
		},
		created() {
			this.getDeviceList()
			this.get_repair_statistics()
			this.get_repair_list()
		},
		mounted() {
			// 初始化图表
			setTimeout(() => {
				this.init_repair_status_chart()
				this.init_repair_trend_chart()
				this.init_maintainer_chart()
			}, 100)
		},
		beforeDestroy() {
			// 销毁图表
			if (this.repair_status_chart) {
				this.repair_status_chart.dispose()
			}
			if (this.repair_trend_chart) {
				this.repair_trend_chart.dispose()
			}
			if (this.maintainer_chart) {
				this.maintainer_chart.dispose()
			}
		},
		watch: {
			repair_status_list: {
				deep: true,
				handler() {
					this.update_repair_status_chart()
				}
			},
			repair_trend_list: {
				deep: true,
				handler() {
					this.update_repair_trend_chart()
				}
			},
			maintainer_list: {
				deep: true,
				handler() {
					this.update_maintainer_chart()
				}
			}
		},
		methods: {
						// 获取设备列表
			getDeviceList() {
				deviceApi.list().then(res => {
					let deviceData = []
					// 处理不同的数据返回格式
					if (Array.isArray(res)) {
						deviceData = res
					} else if (res && res.data) {
						if (Array.isArray(res.data)) {
							deviceData = res.data
						} else if (Array.isArray(res.data.records)) {
							deviceData = res.data.records
						}
					}
					// 构建设备映射表
					deviceData.forEach(device => {
						this.$set(this.deviceMap, device.id, {
							deviceName: device.deviceName || device.name || '未知设备',
							deviceCode: device.deviceCode || device.code || ''
						})
					})
				}).catch(error => {
					console.error('获取设备列表失败:', error)
				})
			},
			handle_size_change(val) {
				this.page_size = val
				this.get_repair_list()
			},
			handle_current_change(val) {
				this.page_num = val
				this.get_repair_list()
			},

			// 重置统计数据
				reset_statistics() {
					this.repair_total = 0
					this.repair_completed = 0
					this.repair_pending = 0
					this.repair_completed_rate = 0
					this.avg_process_time = 0
					this.total_actual_cost = 0
					this.total_estimated_cost = 0
					this.cost_diff_rate = 0
					this.repair_status_list = []
					this.repair_trend_list = []
					this.maintainer_list = []
				},
				
				// 格式化日期
				formatDate(dateString) {
					if (!dateString) return ''
					// 处理ISO 8601格式的时间字符串
					const date = new Date(dateString)
					// 确保日期是有效的
					if (isNaN(date.getTime())) return dateString
					return date.toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit'
					})
				},

			// 获取维修统计数据
			get_repair_statistics() {
				// 获取所有维修工单数据进行统计
				repairApi.list({ size: 1000 }).then(res => {
					try {
						if (res && res.data) {
							const repairs = Array.isArray(res.data) ? res.data : res.data.records || []
							this.repair_total = repairs.length
							
							// 统计各状态工单数量
							this.repair_completed = repairs.filter(r => r.status === 3).length
							this.repair_pending = repairs.filter(r => r.status === 0).length

							// 计算完成率
							if (this.repair_total > 0) {
								this.repair_completed_rate = ((this.repair_completed / this.repair_total) * 100).toFixed(2)
							} else {
								this.repair_completed_rate = 0
							}

							// 计算平均处理时长（简单模拟）
							const completedRepairs = repairs.filter(r => r.status === 3 && r.requestTime && r.completionTime)
							if (completedRepairs.length > 0) {
								const totalHours = completedRepairs.reduce((sum, repair) => {
									// 确保正确处理ISO 8601格式的时间字符串
									const requestDate = new Date(repair.requestTime)
									const completionDate = new Date(repair.completionTime)
									
									// 确保日期有效才进行计算
									if (!isNaN(requestDate.getTime()) && !isNaN(completionDate.getTime())) {
										const hours = (completionDate - requestDate) / (1000 * 60 * 60)
										return sum + (hours > 0 ? hours : 0)
									}
									return sum
								}, 0)
								this.avg_process_time = (totalHours / completedRepairs.length).toFixed(2)
							} else {
								this.avg_process_time = 0
							}

							// 计算成本统计
							const costRepairs = repairs.filter(r => r.status === 3 && r.actualCost !== undefined && r.estimatedCost !== undefined)
							if (costRepairs.length > 0) {
								this.total_actual_cost = costRepairs.reduce((sum, repair) => sum + Number(repair.actualCost || 0), 0)
								this.total_estimated_cost = costRepairs.reduce((sum, repair) => sum + Number(repair.estimatedCost || 0), 0)
								if (this.total_estimated_cost > 0) {
									this.cost_diff_rate = (((this.total_actual_cost - this.total_estimated_cost) / this.total_estimated_cost) * 100).toFixed(2)
								} else {
									this.cost_diff_rate = 0
								}
							} else {
								this.total_actual_cost = 0
								this.total_estimated_cost = 0
								this.cost_diff_rate = 0
							}

							// 统计工单状态
							const statusStats = {}
							repairs.forEach(repair => {
								const status = repair.status || 0
								statusStats[status] = (statusStats[status] || 0) + 1
							})
							this.repair_status_list = Object.keys(statusStats).map(status => ({
								statusName: status === '0' ? '待处理' : status === '1' ? '处理中' : status === '2' ? '已取消' : status === '3' ? '已完成' : '其他',
								count: statusStats[status],
								rate: ((statusStats[status] / this.repair_total) * 100).toFixed(2) + '%'
							}))

							// 统计维修人员工作量
							const maintainerStats = {}
							repairs.forEach(repair => {
								// 使用repairUserId，未分配的显示为"未分配"
								const maintainer = repair.repairUserId ? `维修员${repair.repairUserId}` : '未分配'
								maintainerStats[maintainer] = (maintainerStats[maintainer] || 0) + 1
							})
							this.maintainer_list = Object.entries(maintainerStats)
							.sort((a, b) => b[1] - a[1])
							.map(([name, count]) => ({
								name,
								count
							}))

							// 为每条记录添加deviceName属性
							const repairsWithNames = repairs.map(item => ({
								...item,
								// 将deviceId转换为deviceName
								deviceName: item.deviceId ? `设备${item.deviceId}` : '-'  
							}))

							// 生成任务完成趋势数据（分别统计新建和完成的任务）
							const dateStats = {}
							repairsWithNames.forEach(repair => {
								// 统计新建任务（按申请日期）
								if (repair.apply_time || repair.applyTime || repair.requestTime) {
									const dateValue = repair.apply_time || repair.applyTime || repair.requestTime
									const date = new Date(dateValue).toLocaleDateString()
									if (!dateStats[date]) {
										dateStats[date] = { newTasks: 0, completedTasks: 0 }
									}
									dateStats[date].newTasks++
								}
								
								// 统计完成任务（按完成日期，仅限已完成状态的工单）
								if (repair.status === 3 && (repair.completionTime || repair.completeTime)) {
									const dateValue = repair.completionTime || repair.completeTime
									const date = new Date(dateValue).toLocaleDateString()
									if (!dateStats[date]) {
										dateStats[date] = { newTasks: 0, completedTasks: 0 }
									}
									dateStats[date].completedTasks++
								}
							})
							
							// 转换为图表所需的数据格式
							this.repair_trend_list = Object.entries(dateStats)
							.sort((a, b) => new Date(a[0]) - new Date(b[0]))
							.map(([date, stats]) => ({
								date,
								newTasks: stats.newTasks,
								completedTasks: stats.completedTasks
							}))
						} else {
							this.reset_statistics()
						}
				} catch (error) {
					console.error('处理维修统计数据失败:', error)
					this.reset_statistics()
				}
			}).catch(error => {
				console.error('获取维修统计数据失败:', error)
				this.reset_statistics()
			})
		},

			// 获取工单列表
			get_repair_list() {
				repairApi.list({
					page_num: this.page_num,
					page_size: this.page_size
				}).then(res => {
					if (res && res.data) {
						this.repair_list = res.data.records || []
						this.page_size = res.data.size || this.page_size
						this.page_num = res.data.current || this.page_num
						this.total = res.data.total || 0
						this.repair_total = res.data.total || 0 // 确保分页总数和统计总数一致
					} else {
						this.repair_list = []
					}
			}).catch(error => {
				console.error('获取工单列表失败:', error)
				this.repair_list = []
			})
		},

			// 初始化工单状态图表
			init_repair_status_chart() {
				this.repair_status_chart = this.$echarts.init(document.getElementById('repairStatusChart'))
				this.update_repair_status_chart()
			},

			// 更新工单状态图表
			update_repair_status_chart() {
				if (!this.repair_status_chart) return

				const option = {
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b}: {c} ({d}%)'
					},
					legend: {
						data: this.repair_status_list.map(item => item.statusName)
					},
					series: [
							{
								name: '工单状态',
								type: 'pie',
								radius: '55%',
								center: ['50%', '60%'],
								data: this.repair_status_list.map(item => ({
									value: item.count,
									name: item.statusName
								})),
								emphasis: {
									itemStyle: {
										shadowBlur: 10,
										shadowOffsetX: 0,
										shadowColor: 'rgba(0, 0, 0, 0.5)'
									}
								}
							}
					]
				}

				this.repair_status_chart.setOption(option)
			},

			// 初始化工单趋势图表
			init_repair_trend_chart() {
				this.repair_trend_chart = this.$echarts.init(document.getElementById('repairTrendChart'))
				this.update_repair_trend_chart()
			},

			// 更新工单趋势图表
			update_repair_trend_chart() {
				if (!this.repair_trend_chart) return

				const option = {
					title: {
						text: '任务完成趋势',
						left: 'center'
					},
					tooltip: {
						trigger: 'axis',
						formatter: function(params) {
							let result = params[0].name + '<br/>'
							params.forEach(param => {
								result += `${param.marker}${param.seriesName}: ${param.value}<br/>`
							})
							return result
						}
					},
					legend: {
						data: ['新建任务', '完成任务'],
						bottom: 10
					},
					xAxis: {
						data: this.repair_trend_list.map(item => item.date)
					},
					yAxis: {
						type: 'value',
						name: '任务数量',
						min: 0
					},
					series: [
							{
								data: this.repair_trend_list.map(item => item.newTasks),
								type: 'line',
								smooth: true,
								name: '新建任务',
								itemStyle: {
									color: '#409eff'
								},
								lineStyle: {
									color: '#409eff'
								}
							},
							{
								data: this.repair_trend_list.map(item => item.completedTasks),
								type: 'line',
								smooth: true,
								name: '完成任务',
								itemStyle: {
									color: '#67c23a'
								},
								lineStyle: {
									color: '#67c23a'
								}
							}
					]
				}

				this.repair_trend_chart.setOption(option)
			},

			// 初始化维修人员图表
			init_maintainer_chart() {
				this.maintainer_chart = this.$echarts.init(document.getElementById('maintainerChart'))
				this.update_maintainer_chart()
			},

			// 更新维修人员图表
				update_maintainer_chart() {
					if (!this.maintainer_chart) return

					const option = {
						tooltip: {
							trigger: 'axis',
							axisPointer: {
								type: 'shadow'
							},
							formatter: '{b}: {c} 个工单'
						},
						grid: {
							left: '3%',
							right: '4%',
							bottom: '15%',
							containLabel: true
						},
						xAxis: {
							data: this.maintainer_list.map(item => item.name),
							axisLabel: {
								rotate: 45,
								fontSize: 12
							}
						},
						yAxis: {
							type: 'value',
							name: '工单数量',
							namelocation: 'middle',
							nametextStyle: {
								padding: [0, 0, 0, 40]
							}
						},
						series: [
								{
									data: this.maintainer_list.map(item => item.count),
									type: 'bar',
									showBackground: true,
									backgroundStyle: {
										color: 'rgba(180, 180, 180, 0.2)'
									},
									itemStyle: {
										color: function(params) {
											// 为未分配的条目设置不同的颜色
											return params.name === '未分配' ? '#f56c6c' : '#409eff'
										}
									},
									label: {
										show: true,
										position: 'top'
									}
								}
						]
					}

					this.maintainer_chart.setOption(option)
				}
		}
	}
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.card-container {
		margin-bottom: 0;
	}

	.card-header {
		font-size: 16px;
		font-weight: bold;
	}

	.card-box {
		display: flex;
		margin-bottom: 20px;
	}

	.box-card {
		margin-right: 20px;
		flex: 1;
	}

	.box-card:last-child {
		margin-right: 0;
	}

	.num-container {
		padding: 15px 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.num-font {
		font-size: 30px;
		font-weight: bold;
	}

	.green {
		color: #67c23a;
	}

	.red {
		color: #f56c6c;
	}

	.blue {
		color: #409eff;
	}

	.chart-container {
		margin-bottom: 20px;
	}

	.chart-card {
		height: 400px;
	}

	.chart-box {
		height: 350px;
		padding: 10px 0;
	}

	.chart {
		height: 320px;
	}

	.table-container {
		margin-bottom: 20px;
	}

	.table-card {
		overflow: hidden;
	}

	.el-pagination {
		margin-top: 20px;
		float: right;
	}
</style>